//
//  WHNThirdViewController.m
//  YiQiTingShu
//
//  Copyright © 2015年 直到世界的尽头. All rights reserved.
//  Created by dllo on 15/11/5.
//  直播-推荐电台`排行榜 点击推出页

#import "WHNThirdViewController.h"
#import "WHNView.h"
#import "AFTools.h"
#import <UIImageView+WebCache.h>
#import <MBProgressHUD.h>
#import <UIImage+AFNetworking.h>
#import "UIImage+GaussianBlur.h"
#import "PlayerButton.h"
#import "WHNProgramme.h"
#import <MJExtension.h>
#import <Foundation/Foundation.h>
#import "Music.h"
#import "WHNHistoryViewController.h"
#import "CoreDataManager.h"
#import "History.h"

@interface WHNThirdViewController ()<UITableViewDataSource, UITableViewDelegate, WHNViewDelegate>
@property(nonatomic, strong)WHNView *topView;
@property(nonatomic, strong)WHNView *downView;
@property(nonatomic, strong)MBProgressHUD *progressView;
@property(nonatomic, strong)WHNView *programmeView;//节目单
@property(nonatomic, assign)NSInteger flag;
@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)NSMutableArray *dataSource;
@property(nonatomic, strong)CoreDataManager *manager;

@end

@implementation WHNThirdViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view NightWithType:UIViewColorType2];
    [self.view addSubview:self.topView];
    [self.view addSubview:self.downView];
    [self.view addSubview:self.progressView];
    [self.view addSubview:self.programmeView];
    [self.programmeView addSubview:self.tableView];
    
    _manager = [CoreDataManager shareManager];
    [[Music shareInstance].myPlayer pause];
    [PlayerButton shareButton].imageURL = _WHNPic;
    [[PlayerButton shareButton] setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:_WHNPic]]] forState:UIControlStateNormal];
    [PlayerButton shareButton].isPlay = YES;
}
#pragma mark 获取数据
-(void)getData
{
    NSString *string = [NSString stringWithFormat:@"http://live.ximalaya.com/live-web/v1/getProgramDetail?device=android&radioId=%@", _RadioId];
    [AFTools getDataByURLString:string WithDataBlock:^(id data) {
        
        NSDictionary *dic = [data objectForKey:@"result"];
        UIImage *image;
        if (![dic objectForKey:@"playBackgroundPic"]) {
            image = [UIImage imageNamed:@"placeholderZh_Larger"];
        }
        else {
            image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[dic objectForKey:@"playBackgroundPic"]]]];
        }
        _topView.WHNBackImageView.image = [UIImage blurryImage:image withBlurLevel:0.2];
        _topView.WHNBackImageView.alpha = .3;
        _topView.WHNCenterImageView.image = [UIImage imageNamed:@"diantai"];
        _topView.WHNCenterImageView.alpha = .5;
        _topView.TitleLabel.text = [dic objectForKey:@"programName"];
        
        
        if ([dic objectForKey:@"announcerList"]) {
            NSMutableArray *array = [NSMutableArray array];
            for (NSDictionary *anchorDic in [dic objectForKey:@"announcerList"]) {
                [array addObject:[anchorDic objectForKey:@"announcerName"]];
            }
            NSMutableString *string = [NSMutableString string];
            for (NSString *each in array) {
                [string appendFormat:@"%@ ", each];
            }
            if (string.length != 0) {
                _topView.AnchorLabel.text = [NSString stringWithFormat:@"主播:%@", string];
//                play.user = string;
            }
        }
        if (![dic objectForKey:@"startTime"]) {
            _topView.TimeLabel.text = @"暂无信息";
        }
        else {
            _topView.TimeLabel.text = [NSString stringWithFormat:@"%@ ~ %@", [dic objectForKey:@"startTime"], [dic objectForKey:@"endTime"]];
        }
//        play.indexTitle = [NSString stringWithFormat:@"%@ ~ %@", [dic objectForKey:@"startTime"], [dic objectForKey:@"endTime"]];
        
        [_topView.WHNListButton addTarget:self action:@selector(programmeAction) forControlEvents:UIControlEventTouchUpInside];
        [_topView.WHNHistoryButton addTarget:self action:@selector(historyListAction) forControlEvents:UIControlEventTouchUpInside];
        
        //下部详情
        [_downView.WHNCenterImageView sd_setImageWithURL:[NSURL URLWithString:_WHNPic] placeholderImage:[UIImage imageNamed:@"placeholderZh"]];
        
        _downView.TitleLabel.text = _Rname;
        _downView.AnchorLabel.text = [NSString stringWithFormat:@"正在直播: %@", [dic objectForKey:@"programName"]];
        CGFloat a = [_WHNCount integerValue] / 10000;
        if (a > 0) {
            _downView.TimeLabel.text = [NSString stringWithFormat:@"%.1f万人", a];
        }
        else {
            _downView.TimeLabel.text = [NSString stringWithFormat:@"%@人", _WHNCount];
        }
        _downView.TimeLabel.font = [UIFont systemFontOfSize:12];
        
        if (![_manager radioHistoryIsExist:_RadioId]) {
            History *play = [NSEntityDescription insertNewObjectForEntityForName:@"History" inManagedObjectContext:_manager.managedObjectContext];
            
            //给属性赋值
            play.imageUrl = _WHNPic;
            play.rname = _Rname;
            play.radioId = [NSString stringWithFormat:@"%@", _RadioId];
            play.title = [dic objectForKey:@"programName"];
            play.acount = [NSString stringWithFormat:@"%@", _WHNCount];
           
            
            [_manager saveContext];
        }
         [_progressView removeFromSuperview];
    }];
}
-(void)getListData
{
    _dataSource = [NSMutableArray array];
    [AFTools getDataByURLString:[NSString stringWithFormat:@"http://live.ximalaya.com/live-web/v1/getProgramSchedules?device=iPhone&radioId=%@", _RadioId] WithDataBlock:^(id data) {
        NSMutableArray *yesterdayArr = [NSMutableArray array];
        NSMutableArray *todayArr = [NSMutableArray array];
        NSMutableArray *tomorrowArr = [NSMutableArray array];
        yesterdayArr = [WHNProgramme mj_objectArrayWithKeyValuesArray:[[data objectForKey:@"result"] objectForKey:@"yesterdaySchedules"]];
        todayArr = [WHNProgramme mj_objectArrayWithKeyValuesArray:[[data objectForKey:@"result"] objectForKey:@"todaySchedules"]];
        for (WHNProgramme *each in todayArr) {
            //获取当前时间
            NSDate *date = [NSDate date];
            NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
            [formatter setDateFormat:@"HH"];
            NSString *timeString= [formatter stringFromDate:date];
            if ([timeString integerValue] >= [[[each.startTime componentsSeparatedByString:@":"] objectAtIndex:0] integerValue]) {
                [[Music shareInstance] playMusicWith:each.listenBackUrl];
                
//                History *his = [NSEntityDescription insertNewObjectForEntityForName:@"History" inManagedObjectContext:_manager.managedObjectContext];
//                //给属性赋值
//                his.imageUrl = _WHNPic;
//                his.acount = _WHNCount;
//                his.rname = _Rname;
//                his.radioId = [NSString stringWithFormat:@"%@", _RadioId];
//                his.title = each.programName;
//                [_manager saveContext];
            }
        }
        tomorrowArr = [WHNProgramme mj_objectArrayWithKeyValuesArray:[[data objectForKey:@"result"] objectForKey:@"tomorrowSchedules"]];
        [_dataSource addObject:yesterdayArr];
        [_dataSource addObject:todayArr];
        [_dataSource addObject:tomorrowArr];
        [_tableView reloadData];
    }];
}


-(MBProgressHUD *)progressView
{
    if (!_progressView) {
        _progressView = [[MBProgressHUD alloc]initWithView:self.view];
        _progressView.labelText = @"加载中";
        [_progressView setMode:MBProgressHUDModeIndeterminate];
        [_progressView show:YES];
        [_progressView NightWithType:UIViewColorTypeNormal];
    }
    return _progressView;
}
#pragma mark 视图将出现时,上下隐藏
-(void)viewWillAppear:(BOOL)animated
{
    [PlayerButton shareButton].hidden = YES;
    self.tabBarController.tabBar.hidden = YES;
    self.navigationController.navigationBar.translucent = YES;
    self.navigationController.navigationBar.barTintColor = [UIColor clearColor];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"fy_backView"] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.barStyle = UIBarStyleBlackTranslucent;
    self.topView.WHNPlayButton.selected = ![[NSUserDefaults standardUserDefaults] objectForKey:@"button"];
    
    [self getListData];
    [self getData];
    self.title = _Rname;
}
#pragma mark 视图将消失时,上下出现
-(void)viewWillDisappear:(BOOL)animated
{
    [_programmeView removeFromSuperview];
    [PlayerButton shareButton].hidden = NO;
    self.navigationController.navigationBar.translucent = NO;
//    self.tabBarController.tabBar.hidden = NO;
    self.navigationController.navigationBar.barTintColor = [ThemeManage shareThemeManage].color3;
    self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
    self.topView.WHNPlayButton.selected = ![[NSUserDefaults standardUserDefaults] objectForKey:@"button"];
    
}
#pragma mark 上部视图初始化,懒加载
-(WHNView *)topView
{
    if (!_topView) {
        _topView = [[WHNView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 550 * FitHeight)];
        _topView.delegate = self;
        _topView.kind = WHNViewKindLabelLive;
    }
    return _topView;
}
#pragma mark 下部视图初始化,懒加载
-(WHNView *)downView
{
    if (!_downView) {
        _downView = [[WHNView alloc] initWithFrame:CGRectMake(0, _topView.frame.origin.y + _topView.frame.size.height, _topView.frame.size.width, self.view.frame.size.height - _topView.frame.size.height - 64)];
        _downView.kind = WHNViewKindDownDetails;
        [_downView NightWithType:UIViewColorType2];
    }
    return _downView;
}
#pragma mark 节目单初始化,懒加载
-(WHNView *)programmeView
{
    if (!_programmeView) {
        _programmeView = [[WHNView alloc]initWithFrame:CGRectMake(- self.view.frame.size.width, 64, self.view.frame.size.width, 370 * FitHeight)];
        _programmeView.kind = WHNViewKindSegmentControl;
        _programmeView.WHNSegment.selectedSegmentIndex = 1;
        [_programmeView.WHNSegment addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    }
    return _programmeView;
}
#pragma mark 节目单初始化,懒加载
-(UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 50 * FitHeight, self.view.frame.size.width, 320 * FitHeight) style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        [_tableView NightWithType:UIViewColorTypeClear];
    }
    return _tableView;
}
#pragma mark 节目单点击方法
-(void)programmeAction
{
    if (_flag == 0) {
        [UIView animateWithDuration:.5 animations:^{
            _programmeView.frame = CGRectMake(0, 64, self.view.frame.size.width, 370 * FitHeight);
//            [self getListData];
        }];
        _flag = 1;
    }
    else {
        [UIView animateWithDuration:.5 animations:^{
            _programmeView.frame = CGRectMake(- self.view.frame.size.width, 64, self.view.frame.size.width, 370 * FitHeight);
        }];
        _flag = 0;
    }
}
#pragma mark 播放历史单点击方法
-(void)historyListAction
{
    WHNHistoryViewController *hisVC = [[WHNHistoryViewController alloc]init];
//    self.tabBarController.tabBar.hidden = YES;
    hisVC.supVC = self;
    [self.navigationController pushViewController:hisVC animated:YES];
}
-(void)segmentAction:(UISegmentedControl *)segment;
{
    _programmeView.WHNSegment.selectedSegmentIndex = segment.selectedSegmentIndex;
    [_tableView reloadData];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
    }
    if (_dataSource.count != 0) {
        if ([[_dataSource[_programmeView.WHNSegment.selectedSegmentIndex][indexPath.row] playType] integerValue] == 3) {
            cell.textLabel.text = @"暂无节目";
        }
        else {
            cell.textLabel.text = [_dataSource[_programmeView.WHNSegment.selectedSegmentIndex][indexPath.row] programName];
        }
        cell.detailTextLabel.text = [NSString stringWithFormat:@"%@-%@", [_dataSource[_programmeView.WHNSegment.selectedSegmentIndex][indexPath.row] startTime], [_dataSource[_programmeView.WHNSegment.selectedSegmentIndex][indexPath.row] endTime]];
        cell.textLabel.textColor = [UIColor whiteColor];
        cell.detailTextLabel.textColor = [UIColor whiteColor];
    }
    [cell NightWithType:UIViewColorType2];
    switch (_programmeView.WHNSegment.selectedSegmentIndex) {
        case 0:
            cell.textLabel.textColor = [UIColor whiteColor];
            cell.detailTextLabel.textColor = [UIColor whiteColor];
            break;
        case 1:{
            NSDate *date = [NSDate date];
            
            NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
            [formatter setDateFormat:@"HH"];
            NSString *timeString= [formatter stringFromDate:date];
            if ([timeString integerValue] >= [[[[_dataSource[_programmeView.WHNSegment.selectedSegmentIndex][indexPath.row] startTime] componentsSeparatedByString:@":"] objectAtIndex:0] integerValue]) {
                cell.textLabel.textColor = [UIColor whiteColor];
                cell.detailTextLabel.textColor = [UIColor whiteColor];
            }
            else {
                cell.textLabel.textColor = [UIColor colorWithRed:0.33 green:0.39 blue:0.46 alpha:1];
                cell.detailTextLabel.textColor = [UIColor colorWithRed:0.33 green:0.39 blue:0.46 alpha:1];
            }
            break;
        }
        case 2:
            cell.textLabel.textColor = [UIColor colorWithRed:0.33 green:0.39 blue:0.46 alpha:1];
            cell.detailTextLabel.textColor = [UIColor colorWithRed:0.33 green:0.39 blue:0.46 alpha:1];
            break;
            
        default:
            break;
    }
    
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 40 * FitHeight;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_dataSource.count == 0) {
        return 0;
    }
    return [_dataSource[_programmeView.WHNSegment.selectedSegmentIndex]  count];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

- (void)passValue:(BOOL)isPlay {
    if (isPlay) {
        [[Music shareInstance].myPlayer play];
        
    } else {
        [[Music shareInstance].myPlayer pause];
    }
    [PlayerButton shareButton].isPlay = isPlay;
}

-(void)coreDataAction
{
    
}












@end
